package com.hsc.www.cxf.client;

import com.alibaba.fastjson.JSONObject;
import com.hsc.www.cxf.server.Student;
import com.hsc.www.cxf.server.StudentService;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;

/**
 * Created by sky on 2018/2/27.
 */
public class CxfClient {
    //webservice接口地址
    private static String address = "http://127.0.0.1:8080/service/student?wsdl";

    //测试
    public static void main(String[] args) throws Exception {
        test1();
        test2();
    }

    /**
     * 方式1:使用代理类工厂,需要拿到对方的接口
     */
    public static void test1() throws Exception {

        // 代理工厂
        JaxWsProxyFactoryBean factoryBean = new JaxWsProxyFactoryBean();
        // 设置代理地址
        factoryBean.setAddress(address);
        // 设置接口类型
        factoryBean.setServiceClass(StudentService.class);
        //添加用户名密码拦截器
        //factoryBean.getOutInterceptors().add(new LoginInterceptor("root","admin"));;

        // 创建一个代理接口实现
        StudentService appService = (StudentService) factoryBean.create();
        Student result = appService.getStudent(1L);
        System.out.println("返回结果:" + JSONObject.toJSONString(result));

    }

    /**
     * 动态调用方式
     */
    public static void test2() throws Exception {
        // 创建动态客户端
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        Client client = dcf.createClient(address);
        // 需要密码的情况需要加上用户名和密码
        //  client.getOutInterceptors().add(new LoginInterceptor("root", "admin"));

        // invoke("方法名",参数1,参数2,参数3....);
        Object[] objects = client.invoke("getStudentName", 1L);
        System.out.println("返回数据:" + objects[0]);

    }
}
